<template>
  <Form class="xtx-form" :validation-schema="mySchema" v-slot="{errors}" ref="formCom" autocomplete="off">
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{err:errors.mobile}" class="input" type="text" placeholder="绑定的手机号" v-model="form.mobile" name="mobile"/>
      </div>
      <div class="error" v-if="errors.mobile">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{err:errors.code}" class="input" type="text" placeholder="短信验证码"  v-model="form.code" name="code"/>
        <span class="code" @click="send">{{time===0?'发送验证码':`${time}秒后发送`}}</span>
      </div>
      <div class="error" v-if="errors.code">{{errors.code}}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即绑定</a>
  </Form>
</template>

<script>
import QC from 'qc'
import { reactive, ref, onUnmounted } from 'vue'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import Message from '@/components/library/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  components: { Form, Field },
  props: {
    // qq第3方标识
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    // 获取qq头像、名字信息
    const avatar = ref(null)
    const nickname = ref(null)
    if (QC.Login.check()) {
      QC.api('get_user_info').success(res => {
        avatar.value = res.data.figureurl_qq_1
        nickname.value = res.data.nickname
      })
    }

    // 表单双向数据对象
    const form = reactive({
      mobile: null,
      code: null
    })
    // 校验规则对象
    const mySchema = {
      mobile: schema.mobile,
      code: schema.code
    }
    // 发送验证码
    const time = ref(0)
    let timer = null
    const formCom = ref(null)
    const send = async () => {
      // 先检验表单.通过则返回true，否则返回错误文本
      const valid = mySchema.mobile(form.mobile)
      if (valid === true) {
        if (time.value === 0) {
          // 发请求
          await userQQBindCode(form.mobile)
          // 弹成功提示
          Message({ type: 'success', text: '发送成功' })
          // 倒计时
          time.value = 60
          clearInterval(timer)
          timer = setInterval(() => {
            time.value--
            if (time.value <= 0) {
              clearInterval(timer)
            }
          }, 1000)
        }
      } else {
        // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
        formCom.value.setFieldError('mobile', valid)
      }
    }
    // 组件销毁，清掉倒计时
    onUnmounted(() => {
      clearInterval(timer)
      // 重置表单校验规则
      // formCom.value.resetForm()
    })

    // qq绑定手机
    const store = useStore()
    const router = useRouter()
    const submit = async () => {
      // 表单验证通过发请求
      const valid = await formCom.value.validate()
      if (valid) {
        try {
          const data = await userQQBindLogin({ unionId: props.unionId, mobile: form.mobile, code: form.code })
          const { id, account, avatar, mobile, nickname, token } = data.result
          // 账号信息传给vuex，自动存入本地
          store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })
          // 需要先合并完购物车
          store.dispatch('cart/mergeCart').then(() => {
            // 如果是其他跳转过来的，需要跳转回去
            router.push(store.state.user.redirectUrl || '/')
            // 成功消息提示
            Message({ type: 'success', text: '登录成功' })
          })
        } catch (error) {
          // 当请求失败，捕捉失败信息并且提示
          Message({ type: 'error', text: error.response.data.message || '用户信息错误' })
        }
      } else {
        Message({ type: 'error', text: '请正确填写信息' })
      }
    }
    return { avatar, nickname, form, mySchema, send, time, formCom, submit }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
